package controller;

import com.root.health.bean.UserInfo;
import com.root.health.service.RegisterService;
import com.root.health.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class RegisterController {
    @Autowired
    RegisterService registerService;
    @Autowired
    UserService userService;
    /**
     *
     * 用户注册
     */
    @GetMapping(value = {"register"})
    public String registerPage(){

        return "register";
    }
    @PostMapping("register")
    public String registerPage(UserInfo userInfo, HttpSession session, Model model, HttpServletRequest request){
        //从数据库查询对应用户名的用户信息
        UserInfo checkuser = userService.getUserbyName(userInfo.getUserName());
        String checkpwd = request.getParameter("checkpwd");
        //测试用System.out.println(checkuser);

        if(checkuser!=null){
            //判断用户名是否重复
            model.addAttribute("msgforreg","用户名重复，请重新填写");

            return "register";
        }else{
            //判断用户输入的密码与确认密码是否一致
            if(checkpwd.equals(userInfo.getPassword())){
                //调用注册方法
                registerService.userRegister(
                        userInfo.getUserName(), userInfo.getPassword(), userInfo.getPhone(),
                        userInfo.getRealname(), userInfo.getRole(), userInfo.getGender());
                //把注册成功的用户保存并登录
                session.setAttribute("loginUser",userInfo);
                //注册成功后重定向到index，防止表单重复提交
                return "correlation";
                //return "redirect:/index.html";
            }else{
                model.addAttribute("msgforpwd","两次密码不一致，请重新填写");
                return "register";
            }

        }

    }
}
